<template>
  <div class="wrap">
    <div>
      <label class="label">{{$t('message.SurfaceDeform.curveToCurve')}}</label>
      <query-list
        v-model="params.selectedGroup.startCurve"
        :description="$t('message.SurfaceDeform.selectStartCurve')"
        :active="params.queryListActiveMap.startCurves"
        @switchQuery="switchQuery('startCurves')"
        :tipMsg="$t('message.SurfaceDeform.selectStartCurve')">
        <!-- 切换组按钮 -->
        <div class="dialog-row group">
          <div class="group-btn" @click="updateGroup('del')">-</div>
          <div class="group-btn" @click="updateGroup('last')"><</div>
          <div class="group-text">{{$t('message.SurfaceDeform.group')}} {{`${params.selectedGroup.name}`}}</div>
          <div class="group-btn" @click="updateGroup('next')">></div>
          <div class="group-btn" @click="updateGroup('add')">+</div>
        </div>
      </query-list>
      <query-list
        v-model="params.selectedGroup.targetCurve"
        :description="$t('message.SurfaceDeform.selectTargetCurve')"
        :active="params.queryListActiveMap.targetCurves"
        @switchQuery="switchQuery('targetCurves')"
        :tipMsg="$t('message.SurfaceDeform.selectTargetCurve')">
      </query-list>

    </div>

    <div>
      <label class="label">{{$t('message.SurfaceDeform.deformArea')}}</label>
      <query-list
        v-model="params.deformElements"
        :description="$t('message.SurfaceDeform.deformArea')"
        :active="params.queryListActiveMap.deformElements"
        @switchQuery="switchQuery('deformElements')"
        :tipMsg="$t('message.SurfaceDeform.deformArea')">
      </query-list>
    </div>

    <div>
      <div class="d-flex mt-2 align-items-center">
        <el-checkbox v-model="params.selectFixedEle">{{$t('message.SurfaceDeform.selectFixedEle')}}</el-checkbox>
      </div>
      <query-list
        v-if="params.selectFixedEle"
        v-model="params.fixedElements"
        :description="$t('message.SurfaceDeform.fixedElements')"
        :active="params.queryListActiveMap.fixedElements"
        @switchQuery="switchQuery('fixedElements')"
        :tipMsg="$t('message.SurfaceDeform.fixedElements')">
      </query-list>
    </div>
    <div class="d-flex align-items-center">
      <label class="el-form-item__label">{{$t('message.SurfaceDeform.stiffness')}}：</label>
      <el-select v-model.number="params.stiffness" @change="changeStiffness()">
        <el-option
          v-for="item in stiffnessList"
          :key="item.value"
          :label="item.text"
          :value="item.value"/>
      </el-select>
    </div>
    <!--    确认和关闭-->
    <div class="btn">
      <el-button
        type="primary"
        size="small"
        :disabled="!previewFinished"
        @click="confirm">
        {{ $t('message.WingTwistDesignDlg.confirm') }}
      </el-button>
      <el-button
        size="small"
        @click="close">
        {{ $t('message.WingTwistDesignDlg.cancel') }}
      </el-button>
    </div>
  </div>
</template>

<script>
import DialogMixin from "../DialogMixin";
import {surfaceDeformCommand} from "../../../Command/SurfaceDeformCommand";
import {ElementType, EntityType, GeomType} from "../../../modeling/TypeDefine";

export default {
  mixins: [DialogMixin],
  data() {
    return {
      params: {
        deformElements:[],
        fixedElements:[],
        selectFixedEle:false,
        stiffness:1,
        selectedGroup: {
          index: 0,
          name: '1',
          startCurve: [],
          targetCurve: [],
        },
        allGroups:[{
          index: 0,
          name: '1',
          startCurve: [],
          targetCurve: [],
        }],
        queryListActiveMap:{
          startCurves:1,
          targetCurves:0,
          deformElements:0,
          fixedElements:0,
        }
      },
      previewFinished:false,
      // 刚度类型列表
      // stiffnessList: [
      //   {
      //     name: 0,
      //     src: getCommonPic('minimum.svg', 'deformCmd'),
      //     title: this.$t("message.DeformCmd.minimum")
      //   },
      //   {
      //     name: 1,
      //     src: getCommonPic('medium.svg', 'deformCmd'),
      //     title: this.$t("message.DeformCmd.medium")
      //   },
      //   {
      //     name: 2,
      //     src: getCommonPic('maximum.svg', 'deformCmd'),
      //     title: this.$t("message.DeformCmd.maximum")
      //   },
      // ],
      stiffnessList: [
        {text: this.$t("message.SurfaceDeform.minimum"), value: 0},
        {text: this.$t("message.SurfaceDeform.middle"), value: 1},
        {text: this.$t("message.SurfaceDeform.maximum"), value: 2},
      ],
    };
  },

  mounted() {
    surfaceDeformCommand.init(400,300,300,() => {
      surfaceDeformCommand.handlePickElement(data => {
        if(data && data.element && data.element.length > 0){
          data.element.forEach(subElement => {
            if(this.params.queryListActiveMap.startCurves){
              if(subElement.element.type === ElementType.DATUMLINE || subElement.element.type === ElementType.EDGE || subElement.element.type === ElementType.CURVE){
                this.params.allGroups[this.params.selectedGroup.index].startCurve = this.addNonRepeatElement(this.params.allGroups[this.params.selectedGroup.index].startCurve,[subElement.element]);
                this.params.selectedGroup.startCurve = this.addNonRepeatElement(this.params.selectedGroup.startCurve,[subElement.element]);
              }
            }else if(this.params.queryListActiveMap.targetCurves){
              if(subElement.element.type === ElementType.DATUMLINE || subElement.element.type === ElementType.EDGE || subElement.element.type === ElementType.CURVE){
                this.params.allGroups[this.params.selectedGroup.index].targetCurve = this.addNonRepeatElement(this.params.allGroups[this.params.selectedGroup.index].targetCurve,[subElement.element]);
                this.params.selectedGroup.targetCurve = this.addNonRepeatElement(this.params.selectedGroup.targetCurve,[subElement.element]);
              }
            }else if(this.params.queryListActiveMap.deformElements){
              let entityId = subElement.element?.params?.entityRefId;
              if (entityId) {
                surfaceDeformCommand.getEntitiesByIds([entityId], entities => {
                  if(entities.length > 0){
                    let entity = entities[0];
                    if(entity.type === EntityType.SOLID || entity.type === EntityType.SHELL){
                      this.params.deformElements = this.addNonRepeatElement(this.params.deformElements,[entity]);
                    }

                    surfaceDeformCommand.highLightEntityOutline([entityId]);
                  }
                });
              }
            }else if(this.params.queryListActiveMap.fixedElements && this.params.selectFixedEle){
              if(subElement.element.type === ElementType.DATUMLINE || subElement.element.type === ElementType.EDGE || subElement.element.type === ElementType.CURVE){
                this.params.fixedElements = this.addNonRepeatElement(this.params.fixedElements,[subElement.element]);
              }
            }
          })
        }
      })
      // surfaceDeformCommand.handlePickEntity(entitys => {
      //   if(this.params.queryListActiveMap.deformElements){
      //     entitys.forEach(entity => {
      //       if(entity.type === EntityType.SOLID || entity.type === EntityType.SHELL){
      //         this.params.deformElements = this.addNonRepeatElement(this.params.deformElements,[entity]);
      //       }
      //     })
      //   }
      // })

    })
  },

  methods: {
    changePluginContainerHeight() {
      surfaceDeformCommand.changePluginContainerHeight({minWidth: this.$el.clientWidth, maxHeight: this.$el.clientHeight});
    },
    close(){
      surfaceDeformCommand.closeActiveCmd();
    },

    confirm(){
      //如果预览没有完成，不能够进行确认操作
      if(!this.previewFinished){
        return;
      }

      let params = this.getCommandParams(true);
      if(params.EndCrvs.length === 0 || params.StCrvs.length === 0 || params.BaseIds.length === 0){
        return;
      }

      let calculateParams = {
        preview:false,
        deformParam:params,
      }

      surfaceDeformCommand.deformCalculate(calculateParams,result => {

        this.previewFinished = false;
      });
      this.close();
    },
    preview(){
      let params = this.getCommandParams(true);
      if(params.EndCrvs.length === 0 || params.StCrvs.length === 0 || params.BaseIds.length === 0){
        return;
      }

      let calculateParams = {
        preview:true,
        deformParam:params,
      }

      surfaceDeformCommand.deformCalculate(calculateParams,result => {
        if(result.data === 0){
          this.previewFinished = false;
        }else{
          this.previewFinished = true;
        }
      });
    },
    changeStiffness(){

    },
    //更新组
    updateGroup(btnType) {
      let newGroups = [];
      if(btnType === "del"){
        //删除时，先进行数量判断(当只有一组时，无法再进行删除)，然后进行group中所有大于当前的index都减1
        if(this.params.allGroups.length > 1){
          this.params.allGroups.forEach(group =>{
            if(group.index < this.params.selectedGroup.index){
              newGroups.push(group);
            }else if(group.index > this.params.selectedGroup.index){
              group.index -= 1;
              group.name = (group.index + 1).toString();
              newGroups.push(group);
            }
          })
          this.params.allGroups = newGroups;
          //当删除非第一个时，向前一个为当前显示，如果是第一个，则第一个为当前显示
          if(this.params.selectedGroup.index !== 0){
            this.params.selectedGroup = this.params.allGroups[this.params.selectedGroup.index - 1];
          }else{
            this.params.selectedGroup = this.params.allGroups[0];
          }
        }
      }else if(btnType === "add"){
        this.params.selectedGroup = {
          index:this.params.allGroups.length,
          name:(this.params.allGroups.length + 1).toString(),
          startCurve: [],
          targetCurve: [],
        }
        this.params.allGroups.push(this.params.selectedGroup);
      }else if(btnType === "next"){
        if(this.params.selectedGroup.index === this.params.allGroups.length - 1){
          this.params.selectedGroup = this.params.allGroups[0];
        }else{
          this.params.selectedGroup = this.params.allGroups[this.params.selectedGroup.index + 1];
        }
      }else if(btnType === "last"){
        if(this.params.selectedGroup.index === 0){
          this.params.selectedGroup = this.params.allGroups[this.params.allGroups.length - 1];
        }else{
          this.params.selectedGroup = this.params.allGroups[this.params.selectedGroup.index - 1];
        }
      }
    },
    getCommandParams(isPreview) {
      let type = 1;
      let deformPoint = [];
      let direction = {};
      let distance = null;
      let radius = null;
      let deformAxis = {};
      let isReverse = 0;

      let startCurves = [];
      let targetCurves = [];
      this.params.allGroups.forEach(group => {
        if(group.startCurve.length !== 0 && group.targetCurve.length !== 0){
          startCurves.push(group.startCurve);                                                             //初始曲线
          targetCurves.push(group.targetCurve);                                                           //目标曲线
        }
      })

      let deformSolid = this.params.deformElements;                                                       //实体
      let keepFlag = this.params.selectFixedEle ? 1 : 0;
      let uniform = 0;
      let fixed = this.params.fixedElements;     //固定边线

      let deformFace = [];
      let stiffness = this.params.stiffness;
      let accuracy = 0.5;
      let weight = 2.5;
      let boundary = 1;
      let onlyFace = 0;
      let match = 0;
      let reverseTangent = 0;

      let params = {
        Type: type,
        Point: deformPoint,
        Direction: direction,
        Reverse: isReverse,
        Distance: distance,
        Axis: deformAxis,
        StCrvs: startCurves,
        EndCrvs: targetCurves,
        BaseIds: deformSolid,
        KeepFlag: keepFlag,
        KElements: fixed,
        KDeformElements: deformFace,
        Unity: uniform,
        Radius: radius,
        Rigidity: stiffness,
        Accuracy: accuracy,
        Weight: weight,
        HoldBoundary: boundary,
        KDeformFlag: onlyFace,
        Match: match,
        ReverseTangent: reverseTangent,
      }
      return params;
    },
    //激活的选取框
    switchQuery(name) {
      for (const key in this.params.queryListActiveMap) {
        if (key === name){
          this.params.queryListActiveMap[key] = 1;
        }else{
          this.params.queryListActiveMap[key] = 0;
        }
      }
    },

    //去重添加元素列表内容
    addNonRepeatElement(startElements,addElements,multiAdd = true){
      let startIds = [];
      let endElements = [];
      startElements.forEach(startElement =>{
        if(startElement.id && !startIds.includes(startElement.id)){
          startIds.push(startElement.id);
          endElements.push(startElement);
        }
      })

      addElements.forEach(addElement =>{
        if(addElement.id && !startIds.includes(addElement.id)){
          endElements.push(addElement);
        }
      })
      return endElements;
    },
    elementSelectChange(){
      for(let n = 0;n < this.params.allGroups.length;n++){
        if(this.params.allGroups[n].index === this.params.selectedGroup.index){
          this.params.allGroups[n] = this.params.selectedGroup;
          break;
        }
      }
    },
  },

  watch: {
    "params.deformElements": function () {
      this.preview();
    },
    "params.selectedGroup.startCurve": function () {
      this.elementSelectChange();
      this.preview();
    },
    "params.selectedGroup.targetCurve": function () {
      this.elementSelectChange();
      this.preview();
    },
    "params.allGroups.length": function () {
      this.preview();
    },
    "params.fixedElements": function () {
      this.preview();
    },
    "params.stiffness": function () {
      this.preview();
    },
  },
};
</script>
<style scoped>
.wrap {
    font-size: 12px;
}
.result-item .angle-icon {
    font-weight: bold;
    padding: 0 2px;
}
.dialog-query-list .move-buttons {
    margin-right: 35px;
}
.group {
     display: flex;
     justify-content: center;
 }
.group-btn {
    width: 24px;
    height: 24px;
    border: var(--bg-color8) 1px solid;
    border-radius: 3px;
    font-size: 16px;
    text-align: center;
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 2px;
}
.group-btn:hover {
    background-color: var(--bg-color8);
    cursor: pointer;
}
.el-icon-my-message{
    background:url('./minimum.svg') center no-repeat;
    width:21px;
    height:26px;
}
</style>
